package furns.web;

import com.google.gson.Gson;
import com.sun.org.apache.regexp.internal.RE;
import furns.entity.Member;
import furns.service.MemberService;
import furns.service.impl.MemberServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;

import static com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY;

//该servlet处理和Member相关的请求
public class MemberServlet extends BasicServlet {
    private MemberService memberService = new MemberServiceImpl();
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        //获取action
//        String action = req.getParameter("action");
//        //判断不同的action
//        if ("login".equals(action)){
//            login(req,resp);
//        } else if ("register".equals(action)) {
//            register(req,resp);
//        }else {
//            //提示信息
//            resp.getWriter().write("请求action参数错误");
//        }
//    }

    //登录
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("======login=======");
        //如果在登录页面, 用户没有输入内容，就直接提交，后台接收到的是""
        HttpSession session = req.getSession();
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        Member member = memberService.login(new Member(null, username, password, null, null));
        if (member == null) {
            //把登录错误信息,放入到request域
            req.setAttribute("msg", "用户名或者密码错误");
            req.setAttribute("username", username);
            //用户不存在,进行转发
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
        } else {
            //登录成功
            req.setAttribute("username", username);
            session.setAttribute("member", member);

            //将得到member对象放入到session
            req.getSession().setAttribute("member", member);
            //老师做了一个简单处理
            if ("admin".equals(member.getUsername())) {
                req.getRequestDispatcher("/views/manage/manage_menu.jsp")
                        .forward(req, resp);
            } else {
                req.getRequestDispatcher("/views/member/login_ok.jsp")
                        .forward(req, resp);
            }
        }

    }

    //注册
    protected void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("=======register======");
        //获取前端数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        //获取验证码
        String code = req.getParameter("code");
        //从session获取到验证码
        String token = (String) req.getSession().getAttribute(KAPTCHA_SESSION_KEY);

        //立即删除session验证码-->防止验证码重复使用
        req.getSession().removeAttribute(KAPTCHA_SESSION_KEY);
        //如果token不为空，并且和用户提交的验证码一致，就继续
        if (token != null && token.equalsIgnoreCase(code)) {
            //判断是否存在用户名
            if (!memberService.isExistsUsername(username)) {
                Member member = new Member(null, username, password, email, null);
                boolean register = memberService.registerMember(member);
                if (register) {
                    //注册成功，实现转发
                    req.getRequestDispatcher("/views/member/register_ok.jsp").forward(req, resp);
                } else {
                    //注册失败，实现转发
                    req.getRequestDispatcher("/views/member/register_fail.jsp").forward(req, resp);
                }
            } else {
                //用户名存在，转发到登录界面

                req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
            }
        }else {
            //验证码不对
            //返回提示信息
            req.setAttribute("msg","验证码不对");
            //带会一个信息，显示注册选项页（模拟点击）
            req.setAttribute("active","register");
            req.setAttribute("username",username);
            req.setAttribute("email",email);
            req.getRequestDispatcher("/views/member/login.jsp").forward(req, resp);
        }
    }

    //登出
    protected void logout(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //销毁当前用户的session
        HttpSession session = req.getSession();
        session.invalidate();
        //重定向到网站首页
        resp.sendRedirect(req.getContextPath() + "/index.jsp");
    }

    //ajax验证用户名是否存在
    protected void isExistUserName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1. 获取用户名
        String username = req.getParameter("username");
        //2. 调用service
        boolean existsUsername = memberService.isExistsUsername(username);
        //3. 思路
        //(1). 如何返回json格式,
        //(2) {"isExist":false};
        //4. 先使用最最简单拼接
        //String resultJson = "{\"isExist\": " + isExistUsername + "}";
        //将要返回的数据=>map=>json
        HashMap<String,Object> resultMap = new HashMap<>();
        resultMap.put("isExist",existsUsername);
        String regStr = new Gson().toJson(resultMap);
        //5.返回
        resp.getWriter().write(regStr);
    }
}
